package com.glzn.springboot03.util;

/**
 * @author gongjq
 */
public class ByteUtil {
	public static void HexBytes2Bytes(byte[] dstBytes, int startPos, byte[] srcBytes, int srcLen){
		for (int i = 0; i < srcLen / 2; i++) {
			int i1 = (srcBytes[i * 2] & 0xF) << 4 | (srcBytes[i * 2 + 1] & 0xF);
			dstBytes[i + startPos] = (byte) i1;
		}
	}

	public static void HexStr2Hex(byte[] bytes, int len){
		for (int i = 0; i < len; i++) {
			if (bytes[i] >= 'a' && bytes[i] <= 'f'){
				bytes[i] = (byte)(bytes[i] - 'a' + 10);
			}else if (bytes[i] >= 'A' && bytes[i] <= 'F'){
				bytes[i] = (byte)(bytes[i] - 'A' + 10);
			}else if (bytes[i] >= '0' && bytes[i] <= '9'){
				bytes[i] -= '0';
			}
		}
	}

	public static int getCks(byte[] bytes, int size)
	{
		int re=0;
		if(size<9)
		{
			return 257;
		}
		for(int i=4;i<size-2;i++)
		{
			re+=bytes[i];
		}
		re=re<<8;
		re=re>>8;
		return re&0xFF;
	}

	private static String hexString="0123456789ABCDEF";

	public static String encode(byte[] bytes, int len)
	{
		//根据默认编码获取字节数组
		StringBuilder sb=new StringBuilder(len*2);
		//将字节数组中每个字节拆解成2位16进制整数
		for(int i=0;i<len;i++)
		{
			char c = hexString.charAt((bytes[i] & 0xf0) >> 4);
			sb.append(c);
			sb.append(hexString.charAt((bytes[i] & 0x0f)));
		}
		return sb.toString();
	}
}
